import json
from collections import OrderedDict
from django.conf import settings
from django.shortcuts import HttpResponseRedirect, HttpResponse, render
from django.urls import reverse
from django.utils import translation
from apps.mge.management.commands.collect_urls import URLS_RESOLVE_JS, Command as JsResolver
from hte.error.handle import abort_on_error
from hte.error.models import HTEError
from django.views.decorators.cache import cache_page
from .tasks import add
import logging
from django.views.decorators.http import require_safe
from apps.search.core.es_handler import ElasticsearchManager


logger = logging.getLogger('django')


def site_index(req):
    res = add.delay(1, 3)
    logger.info(res.task_id)
    # ElasticsearchManager.update_all()
    return render(req, 'index.html')
    # lang = translation.get_language()
    # carousels = [cc.get_content(lang) for cc in
    #              CarouselContent.objects.filter(published=True).order_by('-pub_date').all()[:5]]
    # return render(req, 'index.html',
    #               {'carousels': carousels,
    #                'count': len(carousels)})


@require_safe
def set_language(req):
    lang = req.GET.get('lang', translation.get_language())
    if translation.check_for_language(lang):
        translation.activate(lang)
        next_page_url = req.GET.get('next', reverse('site_index'))
        response = HttpResponseRedirect(next_page_url)
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang)
        return response
    else:
        abort_on_error(HTEError.INVALID_LANGUAGE)


@cache_page(5 * 60)
def get_js_resolver(req):
    js_patterns = OrderedDict()
    exclude_ns = ['admin']
    JsResolver.handle_url_module(js_patterns, settings.ROOT_URLCONF, exclude_ns)
    return HttpResponse(URLS_RESOLVE_JS + 'Urls._urls=' + json.dumps(js_patterns) + ';',
                        content_type='application/javascript')
